package hot_100;

import java.util.HashSet;

public class 排序链表 {
    public static void main(String[] args) {

    }

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode temp = slow;
        slow = slow.next;
        temp.next = null;
        ListNode lc = sortList(head);
        ListNode rc = sortList(slow);
        ListNode ans = new ListNode();
        temp = ans;
        while (lc != null && rc != null) {
            ListNode net = new ListNode();
            if (lc.val <= rc.val) {
                net.val = lc.val;
                lc = lc.next;
            } else {
                net.val = rc.val;
                rc = rc.next;
            }
            temp.next = net;
            temp = net;
        }
        while (lc != null) {
            ListNode net = new ListNode(lc.val);
            lc = lc.next;
            temp.next = net;
            temp = net;
        }
        while (rc != null) {
            ListNode net = new ListNode(rc.val);
            rc = rc.next;
            temp.next = net;
            temp = net;
        }
        return ans.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
